#include "ota_http.h"
#include "log/log.h"
#include <curl/curl.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>

// 接收响应数据的回调函数
// ptr: 响应数据的指针
// size: 每份数据的长度
// nmemb: 份数
// user_buf: 用户自定义的缓存容器
size_t receive_callback(void *ptr, size_t size, size_t nmemb, void *user_buf)
{
    char *response_data = (char *)ptr;
    char *json_buf = (char *)user_buf;
    int data_len = size * nmemb;
    memcpy(json_buf, response_data, data_len);
    json_buf[data_len] = '\0';

    return data_len;
}

char *ota_http_getJson(char *url)
{
    // 初始化CURL
    CURL *curl = curl_easy_init();
    // 配置url
    curl_easy_setopt(curl, CURLOPT_URL, url);
    // 配置接收响应数据的回调函数
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, receive_callback);
    // 配置用户自定义的缓存容器
    char *json_buf = malloc(1024);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, json_buf);
    // 执行请求
    CURLcode res = curl_easy_perform(curl);
    if (res != CURLE_OK) {
        log_error("请求%s失败", url);
        curl_easy_cleanup(curl);
        free(json_buf);
        return NULL;
    }
    curl_easy_cleanup(curl);
    return json_buf;
}

int ota_http_download(char *url, char *filename)
{

    // 初始化CURL
    CURL *curl = curl_easy_init();
    // 配置url
    curl_easy_setopt(curl, CURLOPT_URL, url);
    // 配置接收响应数据的回调函数
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, fwrite);
    // 配置用户自定义的缓存容器
    FILE * file = fopen(filename, "wb");
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, file);
    // 执行请求
    CURLcode res = curl_easy_perform(curl);
    if (res != CURLE_OK) {
        log_error("请求%s下载失败", url);
        curl_easy_cleanup(curl);
        fclose(file);
        return -1;
    }
    curl_easy_cleanup(curl);
    fclose(file);
    return 0;
}
